<?php


namespace app\api\controller;

use app\api\model\AccountModel;
use app\api\model\TengXunModel;
use app\api\model\UserModel;
use app\api\model\YunXinModel;
use app\api\validate\LoginValidate;
use app\common\controller\Auth;
use think\facade\Cache;

// 引入解密文件 在微信小程序开发文档下载
require_once "../vendor/WeMini/crypt/wxBizDataCrypt.php";
require_once "../vendor/WeMini/crypt/errorCode.php";
class Login extends ApiBase
{

    /**
     *
     * 获取用户手机号
     */
    public function getPhone($code){

        $res = $this->getAccessToken();
        $url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=".$res['access_token'];
        $code1['code'] = $code;
        $info = post(json_encode($code1),$url);
        $data = json_decode($info,true);
        //$data['open_id'] =
        if ($data['errcode'] == 0){

            return $data;
        }else{

            $this->fail('获取手机号失败');
        }
    }


    /**
     *
     * 获取open_id
     */
    public function getOpenId($code){

        $appid = config('WeiXin')['appId'];
        $appsecret = config('WeiXin')['appSecret'];
        $grant_type = "authorization_code"; //授权（必填）
        // 拼接url
        $url = "https://api.weixin.qq.com/sns/jscode2session?"."appid=".$appid."&secret=".$appsecret."&js_code=".$code."&grant_type=".$grant_type;
        $res = json_decode($this->httpGet($url),true);
        return $res;
    }
    /**
     * 授权登录
     */
    public function login(){
        $params = input();
        if (!isset($params['code']) || $params['code'] == ''){

            $this->fail('缺少必要参数code(open_id)');
        }
        if (!isset($params['code1']) || $params['code1'] == ''){

            $this->fail('缺少必要参数code(手机号)');
        }
        $open_id = self::getOpenId($params['code']);
        $data = self::getPhone($params['code1']);

        if (is_array($data)) {

            if (!UserModel::where(['phone' => $data['phone_info']['phoneNumber']])->whereOr(['open_id'=>$open_id['openid']])->find()) {

                $info['open_id'] = $open_id['openid'];
                $info['phone'] = $data['phone_info']['phoneNumber'];
                //$info['pid'] = isset($params['pid']) ? $params['pid'] : 0;
                $user_id = UserModel::insertGetId($info);
                TengXunModel::tengXunIMAdd(['id'=>$user_id]);

                $userInfo = UserModel::userInfo(['id' => $user_id]);
            }else{
                $info['open_id'] = $open_id['openid'];
                $info['phone'] = $data['phone_info']['phoneNumber'];
                $info['update_at'] = time();
                UserModel::where(['open_id' => $open_id['openid']])->update($info);
                $userInfo = UserModel::userInfo(['open_id' => $open_id['openid']]);
                TengXunModel::tengXunIMAdd(['id'=>$userInfo['id']]);
            }
            //$userInfo['id'] = 1;
            $auth = Auth::instance();
            $userInfo = UserModel::userInfo(['id'=>$userInfo['id']],'id,phone,head_img,nickname,hospital_name,self_info,type');
            $token = $auth->token($userInfo['id']);
            $userInfo->setAttr('token', $token);
            //$userInfo['yunXinToken'] = YunXinModel::refreshToken($userInfo['id']);
            $userInfo['userSig'] = TengXunModel::getUserSig($userInfo['id']);
            //$userData['session_key'] = $session_key;

            $this->member = $userInfo;
            $this->successful('授权注册成功！', $userInfo);
        } else {
            return $data;
        }

    }

    public function httpGet($url) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);
        $res = curl_exec($curl);
        curl_close($curl);
        return $res;
    }

    /**
     *
     * 获取AccessToken
     */
    public function getAccessToken(){
        $appid = config('WeiXin')['appId'];
        $appsecret = config('WeiXin')['appSecret'];
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$appsecret}";
        $res = json_decode($this->httpGet($url),true);
       return $res;
    }

    /**
     * 验证码登录
     */
    public function codeLogin(LoginValidate $request){


        $params = $this->request->post();
        if (!$request->scene('codeLogin')->check($params)){

            $this->fail($request->getError());
        }
//        $code = Cache::get($params['phone']);
//        if ($code == false || $code != $params['code']){
//
//            $this->fail('验证码错误,请重新发送');
//        }

        if ($info = UserModel::where(['phone'=>$params['phone']])->find()){

           $res = $info['id'];
        }else{

            $res = UserModel::userEdit(['phone'=>$params['phone']]);
        }

        $auth = Auth::instance();
        $userInfo = UserModel::userInfo(['id'=>$res],'id,phone,head_img,nickname,hospital_name,self_info,type');
        //$userInfo['yunXinToken'] = YunXinModel::refreshToken($userInfo['id']);
        $userInfo['userSig'] = TengXunModel::getUserSig($res);
        //$token = $auth->token($id);
        $userInfo['token'] = $auth->token($res);
        //$userData['session_key'] = $session_key;

        $this->member = $userInfo;
        $this->successful('登录成功！',$userInfo);

    }


}